import {
        list,
        find
} from '../../api/product'
import {addCart, getCart,update} from "../../api/cart"

const util = require('../../utils/util.js')

Component({  
        /**
         * 组件的属性列表
         */
        properties: {
                cartInfoToAttr:{
                        type:Object,
                        value:""
                }
        },

        /**
         * 组件的初始数据
         */
        data: {
                cartInfo:[], //暂存购物车中的信息
                shopId:"",
                thumbnail:"",
                flag: false,
                flagOff:false,
                quantity:0,
                giftCardId: '',
                productId: "", //已选中的商品id
                showConfirm: "", //控制底部按键
                type: "", //判断是不是购物车页面的属性点击进来的
                isClose: "", //控制是关闭弹窗还是跳转订单确认页面
                wrapAnimate: 'wrapAnimate',
                bgOpacity: 0,
                frameAnimate: 'frameAnimate',
                spec1Off: false, //第一属性的开关
                spec2Off: false, //第一属性的开关
                imageSrc: "",
                imageSrcOrl: "",
                price: "", //商品单价
                pricePeriod: "", //价格区间
                stock: "", //库存
                stockSum: 0, //总库存
                productState: true, //商品上下架状态
                minLimit: 1, //最小限购数量
                maxLimit: 0, //最大限购数量
                tagTextList: "", //显示所选的标签列表
                selectProduct: "", //被选中的商品
                currentNum: 1, //被选中的商品数量
                coupons: [], //优惠券
                buyDisabled: false, //立即购买的按键控制器
                addCartDisabled: false, //加购的按键控制器
                promotions: [], //活动
                // spec1: "请选择配色分类", //第一属性
                // spec2: "请选择口味", //第二属性
                //商品的属性列表
                attributeList: [],
                //测试的服务端数据
                tagControlList: [], //测试属性的控制列表
                origionalTagControlList: [],
                response: [],
        },

        // lifetimes:{
        //         attached(){

        //         }
        // },

        /**
         * 组件的方法列表
         */
        methods: {
                maskclick() {
                        this.setData({
                                flag: false
                        })
                        setTimeout(()=>{
                                this.setData({
                                        flagOff: false
                                })
                        },500)
                },

                showAttrDialog(data, cartInfo) {
                        console.info("showAttrDialog---------------")
                        console.info(data)
                        this.data.productId = data.productId
                        this.data.shopId = data.shopId
                        // this.formateResponse(this.data.response)
                        // this.setData({
                        //         productName: this.data.response[0].name,
                        //         flag: true
                        // })
                        find(data.productId).then(
                                res => {
                                  if (res.type == 'success') {
                                    console.info(res)
                                    this.data.response = res.data.products
                                    this.setData({
                                        cartInfo: cartInfo,
                                        productName: res.data.products[0].name,
                                        thumbnail:util.thumbnail(res.data.products[0].thumbnail, 160, 160) ,
                                        flag: true,
                                        flagOff:true
                                })
                                    this.formateResponse(res.data.products)
                                    console.info("res.data.products[0].name--"+res.data.products[0].name)
                                  }
                                }
                              ).catch(error => {})

                },

                //属性标签的选择事件
                selectAttr: function (e) {
                        let attrname = e.currentTarget.dataset.attrname
                        let tagname = e.currentTarget.dataset.tagname
                        let canSelected = e.currentTarget.dataset.canselected
                        let isSelected = e.currentTarget.dataset.isselected
                        if (canSelected) {
                                this.control(attrname, tagname, canSelected, isSelected)
                        }
                },

                //控制函数
                control(attrname, tagname, canSelected, isSelected) {
                        console.info("attrname88888888888888888888888" +attrname)
                        console.info("tagname999999999999999999999999" + tagname)
                        let tagControlList = this.data.tagControlList
                        console.info("tagControlList" + JSON.stringify(tagControlList))
                        let response = this.data.response
                        console.info("response" + JSON.stringify(response))
                        let zeroStockList = [] //零库存列表
                        let haveStockList = [] //非零库存列表
                        // if (canSelected) {
                        if (response.length > 0) {
                                response.map((item) => {
                                        if (tagname == item.spec1 || tagname == item.spec2) {
                                                //console.info("item" + JSON.stringify(item))
                                                if (item.stock > 0) {
                                                        if (attrname == "规格") {
                                                                haveStockList.push(item.spec2)
                                                        } else {
                                                                haveStockList.push(item.spec1)
                                                        }
                                                }
                                        }
                                })
                        }
                        if (tagControlList.length > 0) {
                                if (attrname == "规格") {
                                        haveStockList.map((item) => {
                                                tagControlList.map((item1) => {
                                                        if (item1.attrname == "口味") {
                                                                if (item1.tagname != item) {
                                                                        zeroStockList.push(item1.tagname)
                                                                }
                                                        }
                                                })
                                        })
                                } else {
                                        haveStockList.map((item) => {
                                                tagControlList.map((item1) => {
                                                        if (item1.attrname == "规格") {
                                                                if (item1.tagname != item) {
                                                                        zeroStockList.push(item1.tagname)
                                                                }
                                                        }
                                                })
                                        })
                                }
                        }
                        //console.info("zeroStockList--" + JSON.stringify(zeroStockList))
                        //console.info("haveStockList--" + JSON.stringify(haveStockList))
                        let origionalTagControlList = this.data.origionalTagControlList
                        if (tagControlList.length > 0) {
                                tagControlList.map((item) => {
                                        if (isSelected) {
                                                if (item.tagname == tagname) {
                                                        item.isSelected = false
                                                }
                                                if (item.attrname != attrname) {
                                                        if (origionalTagControlList.length > 0) {
                                                                origionalTagControlList.map((origionalTagControlListItem) => {
                                                                        if (item.tagname == origionalTagControlListItem.tagname) {
                                                                                item.canSelected = origionalTagControlListItem.canSelected
                                                                        }
                                                                })
                                                        }

                                                }
                                        } else {
                                                if (item.attrname == attrname) {
                                                        item.isSelected = false
                                                } else {
                                                        if (zeroStockList.length > 0) {
                                                                zeroStockList.map((zeroStockListItem) => {
                                                                        if (zeroStockListItem == item.tagname) {
                                                                                item.canSelected = false
                                                                        }
                                                                })
                                                        }
                                                        if (haveStockList.length > 0) {
                                                                haveStockList.map((haveStockListItem) => {
                                                                        if (haveStockListItem == item.tagname) {
                                                                                item.canSelected = true
                                                                        }
                                                                })
                                                        }
                                                }
                                                if (item.tagname == tagname) {
                                                        item.isSelected = true
                                                }

                                        }

                                })
                        }

                        // }

                        // let tagControlList = this.data.tagControlList
                        let attributeList = this.data.attributeList
                        console.info("attributeList--" + JSON.stringify(attributeList))
                        let spec1 = ""
                        let spec2 = ""

                        if (tagControlList.length > 0) {
                                tagControlList.map((item) => {
                                        if (attributeList.length > 0) {
                                                attributeList.map((item1) => {
                                                        if (item.attrname == item1.attrname) {
                                                                if (item1.tagList.length > 0) {
                                                                        item1.tagList.map((item2) => {
                                                                                if (item.tagname == item2.tagname) {
                                                                                        item2.isSelected = item.isSelected
                                                                                        item2.canSelected = item.canSelected
                                                                                }
                                                                        })
                                                                }
                                                        }
                                                        if (item.isSelected == true) {
                                                                if (item.attrname == "规格") {
                                                                        spec1 = item.tagname
                                                                } else {
                                                                        spec2 = item.tagname
                                                                }
                                                        }
                                                })
                                        }
                                })
                        }
                        // //console.info("spec1.length--" + spec1)
                        // //console.info("spec2.length--" + spec2)
                        let selectProduct = ""
                        let tagTextList = this.data.tagTextList
                        // if (!isSelected){
                        if (response.length > 0) {
                                if (attributeList.length == 2) {
                                        response.map((item) => {
                                                // //console.info("item--" + JSON.stringify(item))
                                                if (item.spec2 == spec2 && item.spec1 == spec1) {
                                                        //console.info("我进来了")
                                                        selectProduct = item
                                                }
                                        })
                                        if (spec1 == "" && spec2 == "") {
                                                tagTextList = ""
                                                selectProduct = ""
                                        } else if (spec1 != "" && spec2 != "") {
                                                tagTextList =  spec1 + "，" + spec2
                                        } else if (spec1 != "") {
                                                tagTextList = spec1
                                                selectProduct = ""
                                        } else {
                                                tagTextList = spec2
                                                selectProduct = ""
                                        }
                                } else if (attributeList.length == 1) {
                                        if (spec1 == "") {
                                                response.map((item) => {
                                                        if (item.spec2 == spec2) {
                                                                selectProduct = item
                                                        }
                                                })
                                                if (spec2 == "") {
                                                        tagTextList = ""
                                                        selectProduct = ""
                                                } else {
                                                        tagTextList = "" + spec2
                                                }
                                        } else if (spec2 == "") {
                                                response.map((item) => {
                                                        if (item.spec1 == spec1) {
                                                                selectProduct = item
                                                        }
                                                })
                                                if (spec1 == "") {
                                                        tagTextList = ""
                                                        selectProduct = ""
                                                } else {
                                                        tagTextList = "" + spec1
                                                }
                                        }
                                }
                        }
                        // }
                        console.info("selectProduct--" + JSON.stringify(selectProduct))
                        let price = this.data.price
                        let stock = this.data.stock
                        let minLimit = this.data.minLimit
                        let maxLimit = this.data.maxLimit
                        let imageSrc = this.data.imageSrc
                        let coupons = this.data.coupons
                        let promotions = this.data.promotions
                        if (selectProduct != "") {
                                price = selectProduct.price
                                stock = selectProduct.stock
                                minLimit = selectProduct.minLimit
                                imageSrc = util.thumbnail(selectProduct.thumbnail, 200, 200)
                                coupons = selectProduct.coupons
                                promotions = selectProduct.promotions
                                if (selectProduct.maxLimit) {
                                        maxLimit = selectProduct.maxLimit
                                }
                        } else {
                                price = this.data.pricePeriod
                                stock = this.data.stockSum
                                imageSrc = this.data.imageSrcOrl
                        }

                        this.setData({
                                currentNum: minLimit > 0 ? minLimit : this.data.currentNum,
                                imageSrc: imageSrc,
                                selectProduct: selectProduct, //被选中的商品
                                attributeList: attributeList,
                                price: price, //商品单价
                                stock: stock, //库存
                                minLimit: minLimit, //限购数量
                                tagTextList: tagTextList, //显示所选的标签列表
                                coupons: coupons,
                                promotions: promotions,
                                maxLimit: maxLimit
                        })
                        this.selectedMatchCartInfo()
                },

                //服务器数据整理
                formateResponse(res) {

                        console.info("服务器数据整理res" + JSON.stringify(res))
                        let spec1List = []
                        let spec2List = []
                        let priceList = []
                        let pricePeriod = this.data.pricePeriod
                        let attributeList = []
                        let stockSum = 0
                        let spec1 = ""
                        let spec2 = ""
                        var imageSrcOrl = ""
                        let productId = parseInt(this.data.productId)
                        console.info("服务器数据整理productId--" + JSON.stringify(productId))
                        let tagTextList = "123"

                        if (res[0].spec1 != "" || res[0].spec2 != "") {
                                tagTextList = ""
                        }
                        console.info("tagTextList--" + JSON.stringify(productId))
                        if (res.length > 0) {
                                res.map((item) => {
                                        if (item.spec1) {
                                                spec1List.push(item.spec1)
                                                if (productId == item.id) {
                                                        spec1 = item.spec1
                                                }
                                        }
                                        if (item.spec2) {
                                                spec2List.push(item.spec2)
                                                if (productId == item.id) {
                                                        spec2 = item.spec2
                                                }
                                        }
                                        priceList.push(item.price)
                                        stockSum += item.stock
                                        item
                                })
                                imageSrcOrl = util.thumbnail(res[0].thumbnail, 200, 200)
                        }
                        console.info("imageSrcOrl--" + imageSrcOrl)

                        //获取初始的价格区间
                        priceList = Array.from(new Set(priceList))
                        if (priceList.length > 1) {
                                pricePeriod = Math.min.apply(Math, priceList) + "-" + Math.max.apply(Math, priceList)
                        } else if (priceList.length > 0) {
                                pricePeriod = priceList[0]
                        }



                        //去重
                        if (spec1List.length > 0) {
                                spec1List = Array.from(new Set(spec1List));
                                tagTextList += "规格"
                                let attributeListItem = {}
                                attributeListItem.attrname = "规格"
                                attributeListItem.tagList = []
                                spec1List.map((item) => {
                                        let num = 0
                                        if (res.length > 0) {
                                                res.map((item1) => {
                                                        if (item1.spec1 == item) {
                                                                num += item1.stock
                                                        }
                                                })
                                        }
                                        let tagListItem = {}
                                        if (num == 0) {
                                                tagListItem.canSelected = false
                                        } else if (num > 0) {
                                                tagListItem.canSelected = true
                                        }
                                        if (spec1 == item) {
                                                tagListItem.isSelected = true
                                        } else {
                                                tagListItem.isSelected = false
                                        }
                                        tagListItem.haveImage = false
                                        tagListItem.tagname = item
                                        attributeListItem.tagList.push(tagListItem)
                                })
                                attributeList.push(attributeListItem)
                        }
                        if (spec2List.length > 0) {
                                spec2List = Array.from(new Set(spec2List));
                                tagTextList += " 口味"
                                let attributeListItem = {}
                                attributeListItem.attrname = "口味"
                                attributeListItem.tagList = []
                                spec2List.map((item) => {
                                        let num = 0
                                        if (res.length > 0) {
                                                res.map((item1) => {
                                                        if (item1.spec2 == item) {
                                                                num += item1.stock
                                                        }
                                                })
                                        }
                                        let tagListItem = {}
                                        if (num == 0) {
                                                tagListItem.canSelected = false
                                        } else if (num > 0) {
                                                tagListItem.canSelected = true
                                        }
                                        if (spec2 == item) {
                                                tagListItem.isSelected = true
                                        } else {
                                                tagListItem.isSelected = false
                                        }
                                        tagListItem.haveImage = false
                                        tagListItem.tagname = item
                                        attributeListItem.tagList.push(tagListItem)
                                })
                                attributeList.push(attributeListItem)
                        }
                        console.info("attributeList-- " + JSON.stringify(attributeList))
                        let tagControlList = []
                        let origionalTagControlList = []
                        if (attributeList.length > 0) {
                                attributeList.map((item) => {
                                        if (item.tagList.length > 0) {
                                                item.tagList.map((item1) => {
                                                        let tagControlListItem = {}
                                                        tagControlListItem.attrname = item.attrname
                                                        tagControlListItem.haveImage = item1.haveImage
                                                        tagControlListItem.isSelected = item1.isSelected
                                                        tagControlListItem.canSelected = item1.canSelected
                                                        tagControlListItem.tagname = item1.tagname
                                                        tagControlList.push(tagControlListItem)
                                                        let origionalTagControlListItem = {}
                                                        origionalTagControlListItem.attrname = item.attrname
                                                        origionalTagControlListItem.haveImage = item1.haveImage
                                                        origionalTagControlListItem.isSelected = item1.isSelected
                                                        origionalTagControlListItem.canSelected = item1.canSelected
                                                        origionalTagControlListItem.tagname = item1.tagname
                                                        origionalTagControlList.push(origionalTagControlListItem)
                                                })
                                        }
                                })

                        }

                        console.info("tagControlList-- " + JSON.stringify(tagControlList))
                        this.setData({
                                origionalTagControlList: origionalTagControlList,
                                tagControlList: tagControlList,
                                attributeList: attributeList,
                                pricePeriod: pricePeriod,
                                price: pricePeriod,
                                stockSum: stockSum,
                                imageSrcOrl: imageSrcOrl,
                                imageSrc: imageSrcOrl,
                                stock: stockSum,
                                tagTextList: tagTextList, //显示所选的标签列表
                        })
                        if (!util.isNull(spec1)) {
                                console.info("我是规格的初始化器spec1--" + spec1)
                                this.control("规格", spec1, true, false)
                        }
                        if (!util.isNull(spec2)) {
                                console.info("我是口味的初始化器spec2--" + spec2)
                                this.control("口味", spec2, true, false)
                        }
                        if (util.isNull(spec1) && util.isNull(spec2)) {
                                let response = this.data.response
                                console.info("response" + JSON.stringify(response))
                                if (response.length > 0) {
                                        response.map(item => {
                                                if (item.id == productId) {
                                                        this.data.selectProduct = item
                                                        console.info("this.data.selectProduct" + JSON.stringify(this.data.selectProduct))
                                                        if (this.data.selectProduct.minLimit > 0) {
                                                                this.setData({
                                                                        currentNum: this.data.selectProduct.minLimit,
                                                                        minLimit: this.data.selectProduct.minLimit
                                                                })
                                                        }
                                                        if (this.data.selectProduct.minLimit > 0) {
                                                                this.setData({
                                                                        maxLimit: this.data.selectProduct.maxLimit
                                                                })
                                                        }
                                                }
                                        })
                                }

                        }

                },

                //属性点击时切换匹配购物车中的商品
                selectedMatchCartInfo(){
                        let _this = this
                        console.info("_this.data.cartInfo--")
                        console.info(_this.data.cartInfo)
                        if(_this.data.selectProduct != "" && _this.data.cartInfo.itemVoList.length > 0){
                                let off = true
                                _this.data.cartInfo.itemVoList.map(item => {
                                        if(item.productId == _this.data.selectProduct.id){
                                                _this.setData({
                                                        quantity : item.quantity
                                                }) 
                                                off = false  
                                        }
                                })
                                if(off){
                                        _this.setData({
                                                quantity :0
                                        })
                                }
                        }else if(_this.data.selectProduct == "" || _this.data.cartInfo.itemVoList.length == 0){
                                _this.setData({
                                        quantity :0
                                })
                        }
                        console.info("匹配购物车后quantity--"+this.data.quantity)
                },

                //获取购物车信息
                getCart(callback){
                        let params = {
                                shopId:this.data.shopId
                        }
                        getCart(params).then(
                                res => {
                                  console.log("getCart--" + JSON.stringify(res))
                                if (res.type == 'success') {
                                        this.setData({
                                                cartInfo:res.data.cart
                                        })
                                        this.selectedMatchCartInfo()
                                        if(callback){
                                        callback(res.data)
                                        }
                                }
                                }
                        ).catch(error => {})
                },

                //添加购物车
                addCart(e){
                        let _this = this
                        console.info(e)
                        if(_this.data.selectProduct == ""){
                                
                                wx.showToast({
                                        title: '成功',
                                        icon: 'none',
                                        duration: 2000
                                })
                                
                        }else{
                                console.info(_this.data.selectProduct)
                                let sendData = {
                                        productId: _this.data.selectProduct.id,
                                        type:"add",
                                        shopId: _this.data.shopId, 
                                        clientX: e.touches[0].clientX,
                                        clientY: e.touches[0].clientY
                                }
                                        let params = {
                                                productId: _this.data.selectProduct.id,
                                                quantity:1,
                                                shopId:_this.data.shopId
                                        }
                                        addCart(params).then(
                                                res => {
                                                //   console.log("addCart--" + JSON.stringify(res))
                                                  if (res.type == 'success') {
                                                        _this.getCart(()=>{
                                                        _this.triggerEvent('reloadCartFromAttr', sendData)
                                                        })
                                                        
                                                    }
                                                }
                                              ).catch(error => {})
                        }
                },

                //减少购物车
                reduceCart(){
                        let _this = this
                        let cartId = ""
                        let sendData = {
                                type:"reduce",
                                shopId: _this.data.shopId, 
                                clientX: "",
                                clientY: ""
                        }
                        if(_this.data.quantity > 0){
                                if(_this.data.cartInfo.itemVoList.length > 0){
                                        _this.data.cartInfo.itemVoList.map(item => {
                                                if(item.productId == _this.data.selectProduct.id){
                                                        cartId = item.id
                                                }
                                        })
                                }
                                let data = [{
                                        id:cartId,
                                        quantity:_this.data.quantity - 1,
                                        chk : true
                                }]
                                update(data).then(
                                        res => {
                                        //   console.log("addCart--" + JSON.stringify(res))
                                          if (res.type == 'success') {
                                                _this.getCart(()=>{
                                                _this.triggerEvent('reloadCartFromAttr', sendData)
                                                })
                                            }
                                        }
                                      ).catch(error => {})
                        }
                }
        }
})
